package com.topone.controller;

import com.topone.Const.FanzoneServiceConst;
import com.topone.Converter.BussinessForm2BussinessUrl;
import com.topone.Converter.BussinessForm2OBussinessDTOConvert;
import com.topone.Enum.BussinessStatusEnum;
import com.topone.Enum.ShopApplyStatusEnum;
import com.topone.Exception.FanZoneException;
import com.topone.Form.BussinessForm;
import com.topone.Utils.CodeUntil;
import com.topone.Utils.DaoUtils;
import com.topone.Utils.KeyUntil;
import com.topone.Utils.ResultVOUntil;
import com.topone.VO.ResultVO;
import com.topone.dataObject.BusinessUrl;
import com.topone.dataObject.Bussiness;
import com.topone.dataObject.ShopApply;
import com.topone.dto.BussinessDTO;
import com.topone.service.BusinessUrlService;
import com.topone.service.BussinessService;
import com.topone.service.ShopApplyService;
import com.topone.service.TcCouponService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import weixin.popular.bean.poi.Business;

import javax.transaction.Transactional;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Created by Administrator on 2018/2/4,0004.
 */
@CrossOrigin
@RestController
@RequestMapping("/seller/bussiness")
@Slf4j
public class SellBussinessController extends BaseController {

    @Autowired
    private BussinessService bussinessService;

    @Autowired
    private TcCouponService couponService;

    @Autowired
    private BusinessUrlService businessUrlService;

    @Autowired
    private ShopApplyService shopApplyService;


    @RequestMapping(value = "/list",
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResultVO list(@RequestParam(value = "bussinessCode", required = false) String bussinessCode,
                         @RequestParam(value = "bussinessStatus", required = false) Integer bussinessStatus,
                         @RequestParam(value = "bussinessName", required = false) String bussinessName,
                         Map<String, Object> map) {
        if (bussinessStatus != null) {
            Bussiness bussiness = new Bussiness();
            bussiness.setBussinessStatus(bussinessStatus);
            if (StringUtils.isNotEmpty(bussinessName)) {
                bussiness.setBussinessName(bussinessName);
                List<BussinessDTO> bussinessDTOList = bussinessService.findBussinessNameList(bussiness);
                map.put("bussinessList", bussinessDTOList);
                return ResultVOUntil.success(map);
            } else if (StringUtils.isNotEmpty(bussinessCode)) {
                bussiness.setBussinessCode(bussinessCode);
                List<BussinessDTO> bussinessList = bussinessService.findByBussinessCode(bussiness);
                map.put("bussinessList", bussinessList);
                log.info("[根据商家code查询成功],{}", map);
                return ResultVOUntil.success(map);
            } else {
                List<BussinessDTO> bussinessList = bussinessService.list(bussinessStatus);
                map.put("bussinessList", bussinessList);
                return ResultVOUntil.success(map);
            }
        } else {
            List<Bussiness> bussinessList = bussinessService.findAll();
            map.put("bussinessList", bussinessList);
            return ResultVOUntil.success(map);
        }
    }

    @GetMapping("/detail")
    public ResultVO index(@RequestParam("bussinessCode") String bussinessCode,
                          Map<String, Object> map) {
        if (StringUtils.isNotEmpty(bussinessCode)) {
            List<Bussiness> bussinessList = bussinessService.findList(bussinessCode);
            map.put("bussinessList", bussinessList);
            return ResultVOUntil.success(map);
        } else {
            return ResultVOUntil.error(1, "参数为空");
        }
    }

    @GetMapping("/check")
    @Transactional
    public ResultVO<Map<String, Object>> check(@RequestParam("bussinessId") String bussinessId,
                                               @RequestParam("bussinessCode") String bussinessCode,
                                               @RequestParam("status") Integer status,
                                               Map<String, Object> map) {

        Bussiness bussiness = bussinessService.findOne(bussinessCode, bussinessId);
        if (Objects.isNull(bussiness)) {
            log.debug("无商家信息");
            return ResultVOUntil.error(1, "无商家信息");
        }
        if ((status == BussinessStatusEnum.suceess.getCode()
                && bussiness.getBussinessStatus() == BussinessStatusEnum.Prepare.getCode())
                || (status == BussinessStatusEnum.LEFT.getCode()
                && bussiness.getBussinessStatus() == BussinessStatusEnum.suceess.getCode())) {
            bussiness.setBussinessStatus(status);
            bussinessService.save(bussiness, null);
            if (bussiness.getBussinessStatus() == BussinessStatusEnum.LEFT.getCode()) {
                log.info("商家关店，下架所有优惠券:{}", bussinessId);
                couponService.updateCouponStatus(bussinessId);
            }
            map.put("success", "审核成功");
            return ResultVOUntil.success(map);
        } else {
            return ResultVOUntil.error(1, "商家状态不正确");
        }
    }

    @PostMapping(value = "/save")
    public ResultVO save(@RequestBody BussinessForm bussinessForm) {
        Map<String, Object> maps = new HashMap<>();
        if (Objects.nonNull(bussinessForm)) {
            log.info("bussinessForm:{}", DaoUtils.toJson(bussinessForm));
        } else {
            log.info("bussinessForm no data!!");
            return ResultVOUntil.error(1, "bussinessForm is null");
        }
        Bussiness bussiness = BussinessForm2OBussinessDTOConvert
                .convert(bussinessForm);
        BusinessUrl businessUrl = BussinessForm2BussinessUrl.convert(bussinessForm);

        if (StringUtils.isNotEmpty(bussinessForm.getBussinessPhone())
                && StringUtils.isEmpty(bussiness.getBussinessCode())) {
            if (Objects.nonNull(bussinessService.findByPhone(bussinessForm.getBussinessPhone()))) {
                maps.put("error", "手机号码已使用");
                return ResultVOUntil.error(1,"手机号码已使用");
            }
        }

        //后台新增店铺或者添加分店
        if (StringUtils.isEmpty(bussinessForm.getBussinessCode())) {
            bussiness.setBussinessCode(CodeUntil.getBussinessCode());
        }
        //修改申请表信息
        if (StringUtils.isNotEmpty(bussinessForm.getApplyId())) {
            ShopApply shopApply = shopApplyService.findOne(bussinessForm.getApplyId());
            if (Objects.nonNull(shopApply) && shopApply.getApplyStatus() == ShopApplyStatusEnum.WAIT.getCode()) {
                shopApply.setApplyStatus(ShopApplyStatusEnum.SUCCESS.getCode());
                shopApplyService.save(shopApply);
                log.info("更新商家申请状态成功：ID={}", shopApply.getShopId());
                bussiness.setBussinessId(shopApply.getShopId());
                businessUrl.setBussinessId(bussiness.getBussinessId());
                bussiness.setBussinessStatus(BussinessStatusEnum.suceess.getCode());
            } else {
                return ResultVOUntil.error(1, "商家申请状态不正确:" + shopApply.getShopId());
            }
        } else {
            if (StringUtils.isEmpty(bussinessForm.getBussinessId())) {
                bussiness.setBussinessId(KeyUntil.getUniqueKey());
                businessUrl.setBussinessId(bussiness.getBussinessId());
                bussiness.setBussinessStatus(BussinessStatusEnum.suceess.getCode());
            } else {
                //修改商家信息
                Bussiness saveBusiness = bussinessService.getOne(bussinessForm.getBussinessId());
                map(daoDozerBeanMapper, bussiness, saveBusiness);
                saveBusiness.setBussinessStatus(1);
                BusinessUrl saveBusinessUrl = businessUrlService.findOneByBusinessId(businessUrl.getBussinessId());
                if (Objects.nonNull(saveBusinessUrl)) {
                    map(daoDozerBeanMapper, businessUrl, saveBusinessUrl);
                }
                try {
                    bussinessService.save(saveBusiness, null);
                    businessUrlService.save(saveBusinessUrl);
                }catch (FanZoneException e){
                    log.error("修改商家信息失败-->{}", e.getMessage());
                    return ResultVOUntil.error(1, "修改商家信息失败-->" + e.getMessage());
                }
                maps.put("msg", "修改商家信息成功");
                log.info("修改商家信息成功");
                return ResultVOUntil.success(maps);
            }
        }
        try {
            bussinessService.save(bussiness, null);
            businessUrlService.save(businessUrl);
        } catch (FanZoneException e) {
            log.error("保存数据异常-->{}", e.getMessage());
            return ResultVOUntil.error(1, "保存数据异常-->" + e.getMessage());
        }
        maps.put("msg", "商家入驻成功");
        log.info("商家入住成功");
        return ResultVOUntil.success(maps);
    }


}
